package com.luchao.back.common.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
@RequestMapping("/validate")
public class ValidateCodeController {


    @GetMapping("/getValidateCodeImage")
    public void getValidateCodeImage(HttpServletResponse response, HttpSession session) throws IOException {
        response.setHeader("Pragma", "No-Cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expries", 0);

        //生成随机类
        Random random = new Random();

        //设置验证码的位数
        int length = 5;

        //在内存中创建图像
        int width = (int) Math.ceil(length * 12.5), height = 22;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        //获取图形上下文
        Graphics g = image.getGraphics();
        //设置背景颜色
        g.setColor(new Color(230,230,230));
        g.fillRect(0, 0, width, height);
        //画边框
        g.setColor(Color.GRAY);
        g.drawRect(0, 0, width - 1, height - 1);
        //随机产生10条干扰线，使图像中的认证码不易被其他程序探测到
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.setColor(Color.GRAY);
            g.drawLine(x1, y1, x2, y2);
        }

        Color[] colors = {Color.BLACK, Color.BLUE, Color.CYAN, Color.DARK_GRAY, Color.GRAY, Color.GREEN, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED, Color.WHITE, Color.YELLOW};
        String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        String checkCode = "";
        char code;
        int number;
        //产生验证码
        for (int i = 0; i < length; i++) {
            number = random.nextInt(chars.length());
            code = chars.charAt(number);
            checkCode += code + "";
            int bgColorIndex = random.nextInt(colors.length);
            //设置字体，画验证码
            g.setColor(colors[bgColorIndex]);
            g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 16));
            g.drawString(code + "", 12 * i, 18);
        }

        //将认证码存入到session
        session.setAttribute("validateCode", checkCode);
        //图像生效
        g.dispose();
        //输出如想到页面
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

}
